<!-- 外呼技能组 -->
<template>
    <div class="report_main">
      <tabs :tabPane="tabPaneList" v-model="activeName" @tab-click='toSerach(false)' />
      <continer class="webchatContainer">
        <template slot="search">
          <quickSearch v-if="flag"  :advForm="quickSearchForm" ></quickSearch>
          <quickSearch v-else  :advForm="quickSearchForm2" ></quickSearch>
        </template>

        <template v-slot:oprate>
          <el-button style="margin-left:7px" type="primary" size="mini" @click="toSerach(false)">查询</el-button>
          <el-button  size="mini" @click="toSerach(false)">刷新</el-button>
        </template>

        <template v-slot:content>
          <p class="overviewOfConversation">会话整体概览</p>
          <div class="tags">
            <div v-for="i in tagList" class="tag" :key="i.name">
              <div>
                <p class="describe">{{i.name}}<br></p>
                <p class="number">{{i.value}}</p>
              </div>
            </div>
          </div>
          <p class="overviewOfConversation">趋势</p>
          <div id="timeTrend" />
          <p class="overviewOfConversation lh30">
            <span class="xiangqing" style="margin-right: 6px">详情</span>
            <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42  myIcon" style='color: #B3B9C7' v-popover:explainPopover></span>
            <!-- <el-button @click="jisuan(tableData, formulaList)">测试</el-button> -->
            <span class="floatRight" style="cursor: pointer;">
              <span class="slider">
                <span :class="timeState === 'second' ? 'selected':''" @click="timeStateChange('second')">秒</span>
                <span :class="timeState !== 'second' ? 'selected':''" @click="timeStateChange('HMS')">时分秒</span>
              </span>
              <!-- 表头设置 -->
              <el-dropdown trigger="click" @visible-change="headerChange">
                <span class="el-dropdown-link">
                  <i title="自定义表头" class="V7_iconfont V7_iconV7tubiao_zidingyi fz14" :class="isClick? 'icon-active': ''"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <searchCheckBox
                    :data="realHeader"
                    @check-change="handleCheckChange"
                  ></searchCheckBox>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 自定义公式 -->
              <i title="自定义公式" @click="showDrawer" style="margin-left: 20px" class="V7_iconfont V7_iconV7tubiao_gongshi fz14"></i>

              <!-- 导出 -->
              <el-popover
                placement="top"
                width="100"
                trigger="click"
                popper-class="custom-search-pop"
                >
                <p style="margin-top: 6px" class='exportReport' @click="exportReport('part')">导出当前表格</p>
                <p style="margin-bottom: 6px" class='exportReport' @click="exportReport('all')">导出详细信息</p>
                <i  slot="reference" title="导出" style="margin-left: 20px" class="V7_iconfont V7_iconV7tubiao_daochu fz14"></i>
              </el-popover>
            </span>
          </p>

          <uTable style="min-height:150px"  :key="tableKey"  :tableHeaders='actualHeader' :tableData="tableData"></uTable>
          <div style="width: 100%;height: 20px"></div>
        </template>
      </continer>
      <CustomFormula ref='Custom' :nowHeader="nowHeader" :delUrl="delUrl" :formulaType="type" :show.sync='toshow' :formulaList='formulaList' @getCustomFormula='getCustomFormula' @saveCustomFormula='saveCustomFormula' @cancelFun='cancelFun'> </CustomFormula>
      <el-popover
        ref="explainPopover"
        placement="top"
        width="500"
        trigger="hover"
        popper-class="custom-search-pop"
        >
        <div class='explainMain'>
          <p v-for="item in nowHeader.filter(i => i.notes)" :key="item.label"><span style="color:#303753">{{item.label}}: </span><span style="color:#686E84">{{item.notes}}</span></p>
        </div>
      </el-popover>
    </div>
</template>

<script lang='ts'>
import { Component, Vue } from 'vue-property-decorator'
import tabs from '@/components/configCommon/configTabs.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import searchCheckBox from '@/components/configCommon/operate-modules/SearchCheckbox/index.vue'
import { uTable, CustomFormula } from './components/index'
import { commonAction, deepClone, getFormatDateTime, isHasFuncOrMenus } from '@/utils/common'
import { ExportExcel } from '../../../../public/static/js/worker' // 导出
import * as formula from './base/formulaUtil' // 自定义公式相关
import { selfTimeSetting2 } from './base/timeSetting'
import { timeTrend } from './base/tableHeader/queueHeader'
import { incomingTimeTrend, drawCharts, colorList } from './base/echart'
import { CommonModule } from '@/store/modules/common/index'
import { ReportModule } from '@/store/modules/report/index'
@Component({
  name: 'InboundCallReport',
  components: {
    tabs, continer, quickSearch, uTable, searchCheckBox, CustomFormula
  }
})
export default class extends Vue {
  private $store: any
  get nowHeader () {
    return timeTrend
  }

  get type () {
    return this.flag ? 'queue-trend' : 'queue-compare'
  }

  private activeName = 'report_queue_trend'

  private permissionControl () { // tab权限控制
    const arr = ['report_queue_trend', 'report_queue_compare']
    const newArr: any[] = []
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, true)) {
        newArr.push(item)
      }
    })
    this.tabPaneList = this.tabPaneList.filter(item => newArr.indexOf(item._id) > -1)
    this.activeName = this.tabPaneList[0] ? this.tabPaneList[0].name : 'report_queue_trend'
  }

  private tabPaneList = [
    {
      label: '时间趋势',
      name: 'report_queue_trend',
      _id: 'report_queue_trend'
    },
    {
      label: '组间对比',
      name: 'report_queue_compare',
      _id: 'report_queue_compare'
    }
  ]

  private stateOptions: object[] = [
    { name: '半小时', _id: 'half_hour' },
    { name: '一小时', _id: 'hour' },
    { name: '一天', _id: 'day' },
    { name: '月', _id: 'month' },
    { name: '年', _id: 'year' }
  ]

  private quickSearchForm: any = {
    // 快捷检索数据（时间条件，类型）
    form: {
      startTime: [
        // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 23:59:59'
      ],
      queueNumbers: [], // 技能组
      callTypes: '', // 通话类型
      time1: getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0],
      time2: '00:00',
      time3: getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0],
      time4: '24:00',
      dimension: 'half_hour' // 维度
    },

    advSearchOptions: [
      { label: '维度', inputType: 'select', selectData: this.stateOptions, name: 'dimension' },
      // { label: '呼叫时间', inputType: 'dateTimeRange', clearable: false, name: 'startTime'},
      { label: '开始日期', inputType: 'date', name: 'time1' },
      { label: '开始时间', inputType: 'timeselect', name: 'time2' },
      { label: '结束日期', inputType: 'date', name: 'time3' },
      { label: '结束时间', inputType: 'timeselect', name: 'time4' },
      { label: '技能组', inputType: 'select', selectData: this.queueList, name: 'queueNumbers', filterable: true, multiple: true, clearable: true, defaultProp: { label: 'name', value: '_id' } },
      { label: '通话类型', inputType: 'select', selectData: ReportModule.callTypes, name: 'callTypes', clearable: true, defaultProp: { label: 'label', value: 'value' } }
    ],
    selfPickerOptions: selfTimeSetting2
  }

  private quickSearchForm2: any = {
    // 快捷检索数据（时间条件，类型）
    form: {
      startTime: [
        // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 23:59:59'
      ],
      queueNumbers: [], // 技能组
      callTypes: '', // 通话类型
      time1: getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0],
      time2: '00:00',
      time3: getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0],
      time4: '24:00'
    },
    advSearchOptions: [
      { label: '开始日期', inputType: 'date', name: 'time1' },
      { label: '开始时间', inputType: 'timeselect', name: 'time2' },
      { label: '结束日期', inputType: 'date', name: 'time3' },
      { label: '结束时间', inputType: 'timeselect', name: 'time4' },
      // { label: '呼叫时间', inputType: 'dateTimeRange', clearable: false, name: 'startTime'},
      { label: '技能组', inputType: 'select', selectData: this.queueList, name: 'queueNumbers', filterable: true, multiple: true, clearable: true, defaultProp: { label: 'name', value: '_id' } },
      { label: '通话类型', inputType: 'select', selectData: ReportModule.callTypes, name: 'callTypes', clearable: true, defaultProp: { label: 'label', value: 'value' } }

    ],
    selfPickerOptions: selfTimeSetting2
  }

  private tagList = [
    { name: '排队数', prop: 'queueCount', value: '0' },
    { name: '重复来电', prop: 'incomingRepeated', value: '0' },
    { name: '接通数', prop: 'answered', value: '0' },
    { name: '邀评数', prop: 'satisfInvi1', value: '0' },
    { name: '参评数', prop: 'satisfEval', value: '0' }
  ]

  get flag () {
    return this.activeName === 'report_queue_trend'
  }

  private toSerach () {
    this.$nextTick(() => {
      this.dataQuery()
    })
  }

  private valData: any = []
  private dataQuery () {
    const url = this.flag ? '/report/queue/trend' : '/report/queue/compare'
    const data = deepClone(this.flag ? this.quickSearchForm.form : this.quickSearchForm2.form)
    data.startTime = [`${data.time1} ${data.time2}`, `${data.time3} ${data.time4}`]
    delete data.time1
    delete data.time2
    delete data.time3
    delete data.time4
    commonAction({ url, method: 'post', data }).then(res => {
      this.tableData = res.data
      this.valData = res.data
      this.getTotal(res.data)
      this.headerQuery()
      this.chartInit()
    })
  }

  private chartInit () {
    const resizeWidth = document.querySelector('.header-contain')?.scrollWidth || 300
    const data: any = incomingTimeTrend;
    let list: any = [];
    (data.legend.data as any) = this.tagList.map(item => item.name);
    if (this.flag) {
      data.xAxis.data = this.tableData.map((i: any) => i.showTime)
      list = this.tagList.map((item, index) => {
        return {
          name: item.name,
          color: colorList[index],
          type: 'line',
          code: item.prop,
          smooth: true,

          data: this.tableData.map(i => i[item.prop])
        }
      })
    } else {
      data.xAxis.data = this.tableData.map((i: any) => this.queueListObj[i.queueNumber]?.name || i.queueNumber)
      list = this.tagList.map((item, index) => {
        return {
          name: item.name,
          color: colorList[index],
          type: 'bar',
          emphasis: { label: { show: true, position: 'top' } },
          data: this.tableData.map(i => i[item.prop])
        }
      })
    }

    data.series = list
    drawCharts('#timeTrend', data, { width: resizeWidth, height: 300 })
  }

  // #region
    private tableKey = 0
    private isClick = false
    private tableData = []
    private actualHeader: any = []
    // #endregion

  // #region
  private realHeader = []
  private otherHeader = []
  private async headerQuery (flag?: boolean) { // 表头查询
    const url = '/base/report/headers'
    const data = { type: this.flag ? 'queue-trend' : 'queue-compare' }
    // console.log(otherHeader)
    await commonAction({ url, method: 'GET', data }).then(res => {
      if (res.success) {
        this.headerInit(res.data.headers)
        this.getCustomFormula(false, !flag)
      }
    })
  }

  private headerInit (arr: any = [], flag = true) {
    const item = arr?.find(i => i.prop === 'showTime')
    if (item) {
      item.disenable = true
      item.fixed = 'left'
      item.width = '180px'
    }
    const item2 = arr.find(i => i.prop === 'queueNumber')
    if (item2) {
      item2.disenable = true
      item2.fixed = 'left'
      item2.formatter = (row, column, cellValue, index) => {
        if (cellValue === '总计') {
          return '总计'
        }
        return this.queueListObj?.[cellValue]?.name || cellValue
      }
    }
    if (flag) {
      this.$set(this, 'realHeader', arr)
    }
    this.$set(this, 'actualHeader', arr)
    this.tableKey++
  }

  private headerChange (val) { // 表头修改
    if (!val) {
      const url = '/base/report/headers'
      this.actualHeader.forEach(element => {
        if (element.prop.includes('-')) {
          element.isCustomHeader = true
        } else {
          element.isCustomHeader = false
        }
      });
      const data = { type: this.type, headers: this.actualHeader }
      commonAction({ url, method: 'post', data }).then(res => {
        this.headerQuery(true)
      })
    }
  }

  private handleCheckChange (arr, other, item) {
    if (item?.prop) {
      const obj = this.actualHeader.find(i => i.prop === item.prop)
      obj.show = item.show
    } else {
      this.actualHeader = arr
    }
  }

  private delUrl = '/base/report/formulas/del'
  private saveCustomFormula (data, flag) {
    const url = '/base/report/formulas'
    commonAction({ url, method: 'post', data }).then(res => {
      if (res.success) {
        this.toshow = false;
        (this as any).$message.success(flag ? '添加成功' : '修改成功');
        (this.$refs.Custom as any).reset()
        this.getCustomFormula(false, true)
      }
    })
  }

  private cancelFun () {
    (this.$refs.Custom as any).reset()
    this.getCustomFormula(false, true)
  }
  // #endregion

  // #region
  private created () {
    this.permissionControl()
    this.dataQuery()
  }

  private tableLoading = false
  // #endregion

  // #region
  private toshow = false
  private customFormulaHeader: any = []
  private formulaList: any = []
  private showDrawer () {
    this.toshow = true
    this.getCustomFormula()
  }

  private getCustomFormula (ast?: any, flag?: any) {
    const list = deepClone(this.actualHeader)
    const url = '/base/report/formulas'
    const data = { type: this.type }
    commonAction({ url, method: 'GET', data }).then(res => {
      if (res.success) {
        this.$set(this, 'formulaList', res.data)
        this.getCustomFormulaHeader(this.formulaList)
        for (let i = 0; i < list.length; i++) {
          const element = list[i]
          if (element.customized) {
            if (!this.formulaList.find(item => item._id === element.prop)) {
              list.splice(i, 1)
              i--
            }
          }
        }
        this.customFormulaHeader.forEach(element => {
          try {
            if (!(list.find(item => item.prop === element.prop))) {
              list.push(element)
            } else {
              const val = list.find(item => item.prop === element.prop)
              val.label = element.label
            }
          } catch (error) {
            console.error(list)
          }
        })
        this.headerInit(list)
        if (flag) {
          setTimeout(() => {
            let realdata
            const f = this.valData.find(i => i.flag === '总计')
            if (f) {
              realdata = this.valData
            } else {
              realdata = this.valData.concat(this.getTotal(this.valData))
            }
            formula.jisuan(realdata, this.formulaList).then((val: any) => {
              if (!this.valData.length) {
                val = []
              }
              this.timeStateChange('HMS', val)

              this.tableLoading = false
            })
          }, 200)
        }
      }
    })
  }

  private getCustomFormulaHeader (arr: any[]) {
    const list: any = []
    arr.forEach(item => {
      let flag = false
      for (const key in item.variables) {
        if (item.variables[key].includes('Duration')) {
          flag = true
        }
      }
      list.push({
        label: item.formulaName,
        prop: item._id,
        width: 120,
        show: true,
        customized: true,
        formulaStr: item.formulaStr,
        variables: item.variables,
        digits: item.digits,
        HMS: flag,
        isDuration: flag
      })
    })
    this.customFormulaHeader = list
  }

  // #endregion
  private total = {}
  private getTotal (arr) {
    arr = arr || []
    const total: any = {}
    const obj = arr[0] || {}
    Object.keys(obj).forEach(item => {
      total[item] = 0
    })
    for (let i = 0; i < arr.length; i++) {
      const element = arr[i]
      for (const key in total) {
        if (isNaN(element[key])) {
          if ((element[key] + '').includes(':')) {
            total[key] += Number(formula.format(element[key]))
          } else {
            total[key] = 0
          }
        } else {
          total[key] += Number(element[key])
        }
      }
    }
    const tag = this.flag ? 'showTime' : 'queueNumber'
    Object.keys(obj).forEach(item => {
      if (item.endsWith('Rate') && arr.length) {
        total[item] = getNumber(total[item] / arr.length)
      }
      if (item.startsWith('avg') && arr.length) {
        total[item] = getNumber(total[item] / arr.length)
      }
    })
    total.answerRate = getNumber(total.answered / total.queueCount)
    total.satisfEvalRate = getNumber(total.satisfEval / total.satisfInvi1)
    total.avgAbandonedWaitDuration = getNumber(total.waitDuration2 / total.abandoned)
    total.avgCallDuration = getNumber(total.callDuration / total.answered)
    total.avgAnswerWaitDuration = getNumber(total.waitDuration1 / total.answered)
    total.serviceLevel = getNumber(total.answeredInTime / total.queueCount)
    total[tag] = '总计'
    total.flag = '总计'
    this.total = total
    this.totalToTags()
    return total
    function getNumber (val) {
      if (isNaN(val)) {
        return '--'
      }
      if (val === Infinity) {
        return 0
      }
      return val
    }
  }

  private totalToTags () {
    for (let i = 0; i < this.tagList.length; i++) {
      const element = this.tagList[i]
      element.value = this.total[element.prop] || '0'
    }
  }

  private timeState = ''
  private timeStateChange (val, data?: any) {
    data = data || this.tableData
    const nowHeader = this.nowHeader
    const list1 = this.actualHeader.filter(item => item.isDuration)
      .map(i => i.prop)
    const list2 = this.actualHeader.concat(nowHeader).filter(item => item.type === 'percentage').map(i => i.prop)
    const timeTransformation = require('./base/timeConversion')
    this.timeState = val
    const db = val === 'second' ? timeTransformation.formatHSM : timeTransformation.formatSeconds
    data.forEach(element => {
      list1.forEach(r => {
        element[r] = db(element[r])
      })
      list2.forEach(s => {
        element[s] = getval(element[s])
      })
    });
    this.$set(this, 'tableData', deepClone(data))
    this.tableKey++
    function getval (v) {
      if (v === '--') {
        return '--'
      }
      if ((v + '').includes('%')) {
        return v
      }
      if (isNaN(Number(v))) {
        return '0%'
      } else {
        if ((v + '').includes('.')) {
          return Number(v * 100).toFixed(2) + '%'
        } else {
          if (v === 1) {
            return '100%'
          }
          return Number(v * 100).toFixed(2) + '%'
        }
      }
    }
  }

  public get queueList () {
    return CommonModule.publicCache.queueList
  }

  private get queueListObj () {
    return CommonModule.publicCache.queueListObj
  }

  public get userList () {
    return CommonModule.publicCache.userList
  }

  private exportReport (val) {
    const header = deepClone(this.actualHeader)
    const tableData = this.tableData
    const year = new Date().getFullYear() + ''
    const month = new Date().getMonth() + 1 + ''
    const day = new Date().getDay() + ''
    const time = `${year}${month}${day}`
    const name = `${time}-${this.$store.state.common.session.user.agentName || ''}-(${this.flag ? '时间趋势' : '组间对比'})报表`
    delete header[0].formatter
    if (val === 'all') {
      const de = new ExportExcel(header, tableData)
      de.toExport(name)
    } else {
      const de = new ExportExcel(header.filter(item => item.show), tableData)
      de.toExport(name)
    }
  }
}
</script>
<style lang='stylus' scoped>
@import './css/index.styl'
.tags
  height 90px
  .tag
    height unset
</style>
